package offer;

import java.util.HashMap;

public class Offer53 {

    public int findfirst  (int[] nums, int target) {
        //TODO:2023/7/23  使用map
//        HashMap<Integer, Integer> map = new HashMap<>();
//        for (int a : nums
//             ) {
//            map.put(a,map.getOrDefault(a,0)+1);
//        }
//
//        return   map.containsKey(target)?map.get(target):0;

        //TODO:2023/7/23
        int left=0,right=nums.length-1;
        while (left<=right){
            int mid=left+(right-left)/2;
            if (nums[mid]==target){
                right=mid-1;
            } else if (nums[mid]<target){
                left=mid+1;
            }else  if (nums[mid]>target){
                right=mid-1;
            }
        }
        if (left>=nums.length||nums[left]!=target){
            return  -1;
        }
        return left;
    }


    public int  search(int [] nums,int target){
        if (nums.length==0){
            return 0;
        }
        int findfirst = findfirst(nums, target);
        if (findfirst==-1){
            return 0;
        }
        int count=1;
        for (int i = findfirst+1; i < nums.length; i++) {
            if (nums[i]==target){
                count++;
            }else {
                break;
            }

        }
        return  count;
    }

    public static void main(String[] args) {
        Offer53 offer53 = new Offer53();
        int[] arr={1,2,3};
        int search = offer53.search(arr, 2);
        System.out.println(search);
    }

}
